package com.pay.common.conf;

import com.pay.service.PayOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * 监听所有db的过期事件__keyevent@*__:expired"
 * @author lsm
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private PayOrderService payOrderService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对redis数据失效事件，进行数据处理
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
        String expiredKey = message.toString();

        System.out.println("---------------------------------");
        System.out.println(expiredKey);
        System.out.println("---------------------------------");

        if(expiredKey.startsWith("pay_money_")){
            try {
                String money = expiredKey.replace("pay_money_", "");
                payOrderService.invalidByMoney(money);
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
